package com.android.dwt.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.android.dwt.R;
import com.android.dwt.TaskItem;
import com.android.dwt.data.GTDApp;
import com.android.dwt.ui.CalendarAct;
import com.android.dwt.ui.MainAct;
import com.android.dwt.ui.NewTaskAct;
import com.android.dwt.ui.ViewTaskAct;
import com.android.dwt.util.C;

public class ListFrag extends Fragment implements OnEditorActionListener {

	private static final String TAG = "ListFrag";
	
	private ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
	public MySimpleAdapter mAdapter;
	public static Dialog dlg;
	private GridView mGridView;
	private GTDApp mGa;
	private EditText mQuickAdd;
	private MainAct mMain;
	
	public static final int MENU_COMPLETED = Menu.FIRST;
	public static final int MENU_TRASH = Menu.FIRST + 1;

	public static int FLAG = 0;
	public static final int MENU_ID_ADD = Menu.FIRST;
	public static final int MENU_ID_EDIT = Menu.FIRST + 1;
	public static final int MENU_ID_DELETE = Menu.FIRST + 2;
	public static final int DLG_ID_EDIT = 0;
	public static final int DLG_ID_ADD = 1;
	
	private final String[] fromCols = new String[] {
			"item_icon",
			"item_name",
			"item_count" };
	private final int[] toLayouts = new int[] {
			R.id.item_image,
			R.id.item_text,
			R.id.tv_list_count };

	
	private class MySimpleAdapter extends SimpleAdapter {
		
		private LayoutInflater mInflater;
		
		
		private class ViewHolder {
			
			ImageView listImage;
			TextView listName;
			TextView listCount;
//			ImageView listArrow;
		}
		

		public MySimpleAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			
			super(context, data, resource, from, to);
			
			mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
//			return super.getView(position, convertView, parent);
			
			final ViewHolder holder;
			
			Log.e(TAG, "getView position: " + position);
			
			if (convertView == null) {
				
				convertView = mInflater.inflate(R.layout.grid_list_item, null);
				
				holder = new ViewHolder();
				
				holder.listImage = (ImageView) convertView.findViewById(R.id.item_image);
				holder.listName = (TextView) convertView.findViewById(R.id.item_text);
				holder.listCount = (TextView) convertView.findViewById(R.id.tv_list_count);
//				holder.listArrow = (ImageView) convertView.findViewById(R.id.img_arrow);
				
				convertView.setTag(holder);
				
			} else {
				
				holder = (ViewHolder) convertView.getTag();
			}
			
//			convertView.setBackgroundResource(android.R.color.transparent);
			
			// fill data
			holder.listImage.setImageResource((Integer) mGa.lists.get(position).get("item_icon"));
			holder.listName.setText((String) mGa.lists.get(position).get("item_name"));
			
			int count = (Integer) mGa.lists.get(position).get("item_count");
			if (count <= 0) {
				
				holder.listCount.setVisibility(View.INVISIBLE);
				
			} else {
				
				holder.listCount.setVisibility(View.VISIBLE);
				holder.listCount.setText(String.valueOf(count));
			}
//			holder.listCount.setText(((Integer) mGa.lists.get(position).get("item_count")).toString());
			
//			holder.listArrow.setImageResource(R.drawable.arrow_right_24);
//			holder.listArrow.setBackgroundResource(android.R.color.transparent);
			
			return convertView;
		}
		
	}
	
	
	public static ListFrag newInstance() {
    	
		ListFrag list = new ListFrag();

        // Supply num input as an argument.
//        Bundle args = new Bundle();
//        args.putInt("num", num);
//        f.setArguments(args);

        return list;
    }
	
	@Override
	public void onAttach(Activity activity) {
		
		Log.e(TAG, "onAttach is called");
		
		super.onAttach(activity);
		
		mMain = (MainAct) activity;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);

		Log.e(TAG, "now create method is called!");

		mGa = (GTDApp) mMain.getApplication();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		Log.e(TAG, "onCreateView is called");
		
		/*if (container == null) {
			
			Log.e(TAG, "container is null!");
			
		} else {
			
			Log.e(TAG, "container is not null!");
			Log.e(TAG, "container id" + container.getId());
		}*/
		
//		return super.onCreateView(inflater, container, savedInstanceState);
		
		View v = inflater.inflate(R.layout.main1, container, false);
		
		return v;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		
		Log.e(TAG, "onViewCreated is called");
		
		super.onViewCreated(view, savedInstanceState);
		
		getAdapterData();
		mGridView = (GridView) view.findViewById(R.id.gd_list);
		mAdapter = new MySimpleAdapter(
				mMain,
				items,
				R.layout.grid_list_item,
				fromCols,
				toLayouts);
		
		mGridView.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		
		handleEvent(view);

		processListView();
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		
		Log.e(TAG, "onActivityCreated is called");
		
		super.onActivityCreated(savedInstanceState);
		
//		handleEvent();
		
	}
	
	@Override
	public void onStart() {
		
		super.onStart();
		
		Log.e(TAG, "now start method is called!");
	}

	@Override
	public void onPause() {
		
		super.onPause();
		
		Log.e(TAG, "now pause method is called!");
	}

	@Override
	public void onResume() {
		
		super.onResume();
		
		Log.e(TAG, "now resume method is called!");
		
		refreshAdapterData();
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onStop() {
		
		super.onStop();
		
		Log.e(TAG, "now stop method is called!");
	}
	
	@Override
	public void onDestroyView() {
		
		Log.e(TAG, "onDestroyView is called!");
		
		super.onDestroyView();
		
		Log.e(TAG, "mAdapter number: " + mAdapter.getCount());
	}
	
	@Override
	public void onDetach() {
		
		Log.e(TAG, "onDetach is called!");
		
		super.onDetach();
	}
	
	/*@Override
	protected void onRestart() {
		super.onRestart();
		Log.i(TAG, "now restart method is called!");
	}*/

	@Override
	public void onDestroy() {

		Log.e(TAG, "now destroy method is called!");

		// if (mGa.getListCursor() != null)
		// mGa.getListCursor().close();
		// if (mGa.getTaskCursor() != null)
		// mGa.getTaskCursor().close();
		// if (mGa.getDbHelper() != null)
		// mGa.getDbHelper().close();
		// if (mGa.getDb()!=null && mGa.getDb().isOpen())
		// mGa.getDb().close();

		super.onDestroy();
	}

	/*protected void dialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("ȷ��Ҫ�˳���?");
		builder.setTitle("��ʾ");
		builder.setPositiveButton("ȷ��",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				});
		builder.setNegativeButton("ȡ��",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}*/

	private void handleEvent(View view) {
		
		ImageButton new_task = (ImageButton) view.findViewById(R.id.new_task);
		
		new_task.setOnClickListener(new Button.OnClickListener() {
			
			public void onClick(View v) { // setTitle("intent");
				
				Intent itt = new Intent(getActivity(), NewTaskAct.class);
				
				itt.putExtra("list_index", 0);
				itt.putExtra("new_task", true);
				
				startActivity(itt);
			}
		});
		
		new_task.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					
					v.setBackgroundResource(R.drawable.add_btn_pressed);
					
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					
					v.setBackgroundResource(R.drawable.add_task);
				}
				
				return false;
			}
		});
		 
	}

	private void processListView() {
		
		// has been disabled
		/*OnItemLongClickListener oilsl = new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View v,
					int pos, long id) {
				// TODO Auto-generated method stub
				@SuppressWarnings("unchecked")
				HashMap<String, Object> hm = (HashMap<String, Object>) mGridView
						.getItemAtPosition(pos);
				posInTable = ((Long) hm.get("item_index")).longValue();
				String list_name = (String) hm.get("item_name");
				String list_note = (String) hm.get("item_note");
				selected = new ListItem(list_name, list_note);
				// setTitle("long click"+current_str);

				return false;
			}
		};
		mGridView.setOnItemLongClickListener(oilsl);*/
		
		mQuickAdd = (EditText) mMain.findViewById(R.id.et_quick_add);
		mQuickAdd.setOnEditorActionListener(this);
		
		// will show task list
		OnItemClickListener oicl = new OnItemClickListener() {
			
			public void onItemClick(AdapterView<?> parent, View v, int pos,
					long id) {
				
//				@SuppressWarnings("unchecked")
//				HashMap<String, Object> hm = (HashMap<String, Object>) mGridView
//						.getItemAtPosition(pos);
//				posInTable = ((Long) hm.get("item_index")).longValue();
//				selected = mGa.getDbla().getListItem(posInTable);
				// String listName = selected.getListName();

				Intent i;
				
				if (pos == GTDApp.AGENDA) {
					
					i = new Intent(getActivity(), CalendarAct.class);
					
				} else {
					
					i = new Intent(getActivity(), ViewTaskAct.class);
				}

				i.putExtra("list_index", pos);
				i.putExtra("list_status", C.TASK.UNCOMPLETED);

				startActivity(i);
			}
		};
		mGridView.setOnItemClickListener(oicl);
		
       /*OnTouchListener gestureListener = new OnTouchListener() {
    	   
        	public boolean onTouch(View v, MotionEvent event) {
        		
        		Log.e(TAG, "list view onTouch called!");
        		
        		if (event.getAction() == MotionEvent.ACTION_MOVE) {
        			
        			mFling = true;
//        			return true;
        		}
        		
        		if (event.getAction() == MotionEvent.ACTION_UP) {
        			
        			if (mFling) {
            			
//            			mGridView.setClickable(false);
        				return true;
        				
            		} else {
            			
            			mGridView.setClickable(true);
            		}
        			
        		}
        		
        		
        		
        		if (!mGa.mDetector.onTouchEvent(event)) {
        			
        			Log.e(TAG, "gestureDetector ocurred!");
        			
        			return true;
        		}
        		
        		return false;
        	}
        	
        };   
        mGridView.setOnTouchListener(gestureListener);*/
	}
	
	private void refreshAdapterData() {
		
		getAdapterData();
	}
	
	private void getAdapterData() {
		
		HashMap<String, Object> hm;
		
		items.clear();
		
		for (int i=0; i<mGa.lists.size(); i++) 	{
			
			hm = new HashMap<String, Object>();
			
			hm.put("item_icon", (Integer) mGa.lists.get(i).get("item_icon"));
			hm.put("item_name", (String) mGa.lists.get(i).get("item_name"));
			hm.put("item_count", (Integer) mGa.lists.get(i).get("item_count"));
			
			items.add(hm);
		}
		
		return;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		switch (resultCode) {
		
//			case RESULT_OK:
				
//				break;
				
			default:
				break;
		}
		
		// super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override	
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		
		if (actionId == EditorInfo.IME_ACTION_DONE) {
			
			String str = mQuickAdd.getText().toString();
			
			if (str.length() == 0) {
				
				Toast.makeText(getActivity(), "任务不能为空", Toast.LENGTH_LONG).show();
				
				return true;
			}
			
			// create a new task
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			TaskItem newTask = new TaskItem(str, "", (String) mGa.lists.get(0).get("item_name"));
			
			newTask.setContext(mGa.getContexts().get(0));
			newTask.setProject(mGa.getProjects().get(0));
			newTask.setPosition(mGa.getPositions().get(0).getPlace());
			
			newTask.setRemind("");
			newTask.setTags("");
			
			newTask.setCreated(sdf.format(Calendar.getInstance().getTime()));
			
			mGa.getDbta().insertTask(newTask);

			
			// update the counter
			int count = (Integer) mGa.lists.get(0).get("item_count");
			mGa.lists.get(0).put("item_count", ++count);
			
			SharedPreferences prefs = getActivity().getSharedPreferences(GTDApp.strList, GTDApp.MODE);
			Editor editor = prefs.edit();
			
			editor.putInt("List_count[0]", count);
			editor.commit();
			
			refreshAdapterData();
			mAdapter.notifyDataSetChanged();
			
			mQuickAdd.setText("");
			
			Toast.makeText(getActivity(), getString(R.string.msg_add_task), Toast.LENGTH_LONG).show();
		}
		
		return false;
	}

} // end class